﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Markup;
using System.Diagnostics.Contracts;
using ShredTheLog.Api;
using System.Collections;

namespace ShredTheLog.Converters
{
    [MarkupExtensionReturnType(typeof(IEnumerable))]
    public sealed class LanguageListExtension : MarkupExtension
    {
        public bool AllowNull { get; set; }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            var result = Sort(Enum.GetValues(typeof(Language)).Cast<Language>()).Cast<object>();
            return AllowNull ? new object[] { new NullValue() }.Concat(result) : result;
        }

        public static IEnumerable<Language> Sort(IEnumerable<Language> unsorted)
        {
            Contract.Requires(unsorted != null);
            Contract.Ensures(Contract.Result<IEnumerable<Language>>() != null);

            var result =
                from i in unsorted
                let localizedName = LanguagesConverter.Default.Convert(i)
                orderby localizedName
                select i;

            return result.ToArray();
        }
    }

    [MarkupExtensionReturnType(typeof(IEnumerable))]
    public sealed class CountryListExtension : MarkupExtension
    {
        public bool AllowNull { get; set; }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            var result = Sort(Enum.GetValues(typeof(Country)).Cast<Country>()).Cast<object>();
            return AllowNull ? new object[] { new NullValue() }.Concat(result) : result;
        }

        public static IEnumerable<Country> Sort(IEnumerable<Country> unsorted)
        {
            Contract.Requires(unsorted != null);
            Contract.Ensures(Contract.Result<IEnumerable<Country>>() != null);

            var result =
                from i in unsorted
                let localizedName = CountryConverter.Default.Convert(i)
                orderby localizedName
                select i;

            return result.ToArray();
        }
    }

    [MarkupExtensionReturnType(typeof(IEnumerable))]
    public sealed class YesNoListExtension : MarkupExtension
    {
        public bool AllowNull { get; set; }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            var result = Enum.GetValues(typeof(YesNo)).Cast<object>();
            return AllowNull ? new object[] { new NullValue() }.Concat(result) : result;
        }
    }

    public struct NullValue { }
}
